# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from pymongo import MongoClient


class BuyPipeline(object):
    def process_item(self, item, spider):
        client = MongoClient('127.0.0.1', 27017)
        collection = client['ziroom']['z1']
        url = 'http://cd.ziroom.com/z/'
        time_test = item.get('time')
        print(time_test)
        if time_test.find('-') != -1:
            if time_test[4] != 0:
                time_first = time_test[:2]
                time_last = time_test[4:]
                time = '2020年%s月%s日' % (time_first, time_last)
                print('------->', time)
            else:
                time_first = time_test[:2]
                time_last = time_test[5:]
                time = '2020年%s月%s日' % (time_first, time_last)
                print('------->', time)
        else:
            time = '2020年12月11日'
            print('------->', time)

        # 查找是否是包邮
        by_test = item.get('price')
        # print('=======>', by_test)
        if by_test.find('包邮') != -1:
            # 包邮和价格分开
            by = '包邮'
            by_test = by_test.replace('包邮', '')
            # print(by_test,211111111)
            # 生成信息列表
            info_list = [{
                "title": item.get('title'),
                "price": by_test,
                'by': by,
                'time': time,
                'sites': item.get('sites')
            }]
            print("==========>", info_list)
            # 插入数据
            ret = collection.insert_many(info_list)
            return item
        else:
            info_list = [{
                "title": item.get('title'),
                "price": by_test,
                'time': time,
                'sites': item.get('sites')
            }]
            print("==========>", info_list)
            # 插入数据
            ret = collection.insert_many(info_list)
